package org.bikelab.se3.index.siren;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.store.FSDirectory;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.common.SolrInputDocument;
import org.bikelab.se3.index.Se3IndexWriter;
import org.sindice.siren.analysis.TupleAnalyzer;

public class SirenSolrWriter implements Se3IndexWriter {
	private CommonsHttpSolrServer server;

	public SirenSolrWriter() {
	}

	private SolrServer getSolrServer() {
		return server;
	}

	public void open(TaskAttemptContext context) throws IOException {
		String url = "http://i-10-24-8-30:8080/siren";
		server = new CommonsHttpSolrServer(url);
		server.setSoTimeout(1000); // socket read timeout
		server.setConnectionTimeout(100);
		server.setDefaultMaxConnectionsPerHost(100);
		server.setMaxTotalConnections(100);
		server.setFollowRedirects(false); // defaults to false
		// allowCompression defaults to false.
		// Server side must support gzip or deflate for this to have any effect.
		server.setAllowCompression(true);
		server.setMaxRetries(1); // defaults to 0. > 1 not recommended.
		server.setParser(new XMLResponseParser()); // binary parser is used by
													// default
	}

	public void close() throws IOException {
		try {
			getSolrServer().commit();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void write(Text key, Text val) throws IOException {
		SolrServer s = getSolrServer();
		SolrInputDocument doc = new SolrInputDocument();
		doc.addField("url", key.toString(), 1.0f);
		doc.addField("ntriple", val.toString(), 1.0f);
		try {
			s.add(doc);
//			s.commit();
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
	}
}
